package com.terry.sp.configurer;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
public class ConnectorConfig {

    // 开发时要使用内嵌Spring boot，才注入这一个Bean，部署的时候，直接在conf/server.xml里面修改就可以了
    @Bean
    @Profile("dev")
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;

    }

    private Connector redirectConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8080);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;

        /**
         * 如下设置(application-dev.yml里面: server.port: 8088) ：
         *   connector.setScheme("http");
             connector.setPort(8080);
             connector.setSecure(true);
             connector.setRedirectPort(8088);
         运行结果：
             http://localhost:8080/  可访问
             https://localhost:8088/ 可访问
         但是 HTTP 不重定向 HTTPS

         这里改成：
            connector.setSecure(false)，之后:
            HTTP ==> HTTPS
         */
    }
}
